
/**
*┌──────────────────────────────────────────────────────────────┐
*│　描    述：充值中心出入金                                                    
*│　作    者：gaotang                                            
*│　版    本：1.0    模板代码自动生成                                                
*│　创建时间：2019-02-20 15:07:13                             
*└──────────────────────────────────────────────────────────────┘
*┌──────────────────────────────────────────────────────────────┐
*│　命名空间： BestTrader.Cms.Services                                  
*│　类    名： UCInOutCashService                                    
*└──────────────────────────────────────────────────────────────┘
*/
using BestTrader.Cms.Core.Extensions;
using BestTrader.Cms.IRepository;
using BestTrader.Cms.IServices;
using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using BestTrader.Cms.ViewModels;
using AutoMapper;
using BestTrader.Cms.Models;
using Microsoft.Extensions.Options;
using BestTrader.Cms.Core.Options;
using BestTrader.Cms.RmmfSoftServices;

namespace BestTrader.Cms.Services
{
    public class UCInOutCashService : IUCInOutCashService
    {
        private readonly RmmfSoftAccountService _rmmfAccountService;
        private readonly RmmfSoftCashService _rmmfCashService;
        private readonly IUCGomePayDFService _ucGomePayDFService;
        private readonly IUCExchangeRateManagerService _ucExchangeRateManagerService;
        private readonly IDESEncryptService _desService;

        private readonly IUCInOutCashRepository _repository;
        private readonly IUCExchangeRateRepository _ucExchangeRateRepository;
        private readonly IManagerRepository _managerRepository;
        private readonly IManagerBankCardRepository _managerBankCardRepository;
        private readonly IMapper _mapper;
        private readonly SystemBankOption _bankOption;
        

        public UCInOutCashService(RmmfSoftAccountService rmmfAccountService
            , RmmfSoftCashService rmmfCashService
            , IDESEncryptService desService
            , IUCInOutCashRepository repository
            , IUCExchangeRateRepository ucExchangeRateRepository
            , IManagerRepository managerRepository
            , IManagerBankCardRepository managerBankCardRepository
            , IMapper mapper
            , IOptionsSnapshot<SystemBankOption> options
            , IUCExchangeRateManagerService ucExchangeRateManagerService
            , IUCGomePayDFService ucGomePayDFService)
        {
            _rmmfAccountService = rmmfAccountService;
            _rmmfCashService = rmmfCashService;
            _ucGomePayDFService = ucGomePayDFService;
            _desService = desService;
            _ucExchangeRateManagerService = ucExchangeRateManagerService;

            _repository = repository;
            _ucExchangeRateRepository = ucExchangeRateRepository;
            _managerRepository = managerRepository;
            _managerBankCardRepository = managerBankCardRepository;
            _mapper = mapper;
            _bankOption = options.Get("SYS.BANK");
        }

        #region 1. 直客

        #region 1.3 出入金

        public TableDataResult<int> AddOrModifyInCoin(InCashModel item)
        {
            var result = new TableDataResult<int>();
            UCInOutCash entity;
            var now = DateTime.Now;
            if (item.Id == 0)
            {
                //获取用户出入金汇率规则  by 2019/3/11
                var exchangeRate = _ucExchangeRateManagerService.GetInOutExchangeRateByManagerId(item.ManagerId.ToString());
                //var rate = _ucExchangeRateRepository.GetDefaultExchangeRate();
                if (exchangeRate.Data == null)
                {
                    result.ResultCode = ResultCodeAddMsgKeys.CommonExceptionCode;
                    result.ResultMsg = ResultCodeAddMsgKeys.CommonExceptionMsg;
                    return result;
                }
                var manager = _managerRepository.Get(item.ManagerId);
                if (manager == null)
                {
                    result.ResultCode = ResultCodeAddMsgKeys.CommonExceptionCode;
                    result.ResultMsg = ResultCodeAddMsgKeys.CommonExceptionMsg;
                    return result;
                }
                if (manager.BankCard.IsNullOrWhiteSpace())
                {
                    result.ResultCode = ResultCodeAddMsgKeys.CommonExceptionCode;
                    result.ResultMsg = ResultCodeAddMsgKeys.CommonExceptionMsg;
                    return result;
                }

                entity = _mapper.Map<UCInOutCash>(item);
                entity.UserManagerId = item.ManagerId;
                entity.UserName = manager.UserName;
                entity.UserBankProvince = manager.BankProvince;
                entity.UserRealName = manager.RealName;
                entity.UserCardNo = manager.BankCard;
                entity.UserBankType = manager.BankType;
                entity.OrderNo = $"{manager.UserName}{now.ToString("yyyyMMddHHmmss")}";
                entity.MoneyType = exchangeRate.Data.InCoinUnitCode;    //用户入金
                entity.ExchangeRate = exchangeRate.Data.InCoinExchangeRate;    //入金汇率
                entity.RMBMoney = item.Money * exchangeRate.Data.InCoinExchangeRate;


                // 出入金方式： 1.线下； 2. 支付宝； 3.银行卡；
                if (item.CashModel == 2)
                {
                    // 出入金类型： 1.出金；2.线下入金； 3.线上入金；
                    if (item.CashType == 3)
                    {
                        var _rateSale = _ucExchangeRateRepository.GetDefaultExchangeRate().ProjectPrice ?? 100;  //入金汇率
                        var _current = Math.Round(item.Money * _rateSale * 1.005M, 3).ToString();
                        var timeNum = DateTime.Now.Minute / 6;

                        var rmbMoney = ValidMoney(_rateSale, item.Money, timeNum, timeNum);
                        entity.RMBMoney = rmbMoney;
                    }
                }
                entity.State = 3; // 入金待完成
                //entity.CashType = 1;
                //entity.CashModel
                entity.Remark = "用户入金(待充值)";
                entity.IsDelete = false;
                entity.AddTime = now;
                entity.AddManagerId = item.ManagerId;

                if (entity.RMBMoney > 0)
                {
                    result.Data = _repository.Insert(entity) ?? 0;
                    if (result.Data > 0)
                    {
                        result.ResultCode = ResultCodeAddMsgKeys.CommonObjectSuccessCode;
                        result.ResultMsg = ResultCodeAddMsgKeys.CommonObjectSuccessMsg;
                    }
                    else
                    {
                        result.ResultCode = ResultCodeAddMsgKeys.CommonExceptionCode;
                        result.ResultMsg = ResultCodeAddMsgKeys.CommonExceptionMsg;
                    }
                }
                else
                {
                    result.ResultCode = ResultCodeAddMsgKeys.AlipayExceptionCode;
                    result.ResultMsg = ResultCodeAddMsgKeys.AlipayExceptionMsg;
                }
            }
            else
            {
                ////TODO Modify
                //tradeCommission = _repository.Get(item.Id);
                //if (tradeCommission != null)
                //{
                //    _mapper.Map(item, tradeCommission);
                //    tradeCommission.ModifyManagerId = userId;
                //    tradeCommission.ModifyTime = now;
                //    if (_repository.Update(tradeCommission) > 0)
                //    {
                //        result.ResultCode = ResultCodeAddMsgKeys.CommonObjectSuccessCode;
                //        result.ResultMsg = ResultCodeAddMsgKeys.CommonObjectSuccessMsg;
                //    }
                //    else
                //    {
                //        result.ResultCode = ResultCodeAddMsgKeys.CommonExceptionCode;
                //        result.ResultMsg = ResultCodeAddMsgKeys.CommonExceptionMsg;
                //    }
                //}
                //else
                //{
                //    result.ResultCode = ResultCodeAddMsgKeys.CommonFailNoDataCode;
                //    result.ResultMsg = ResultCodeAddMsgKeys.CommonFailNoDataMsg;
                //}
            }
            return result;
        }

        /// <summary>
        /// 验证数据库中数据是否有相同数据
        /// </summary>
        /// <param name="rate"></param>
        /// <param name="money"></param>
        /// <param name="rndNum"></param>
        /// <param name="defaultNum"></param>
        /// <returns></returns>
        private decimal? ValidMoney(decimal rate, decimal money, int rndNum, int defaultNum)
        {
            // 支付宝要收千分之五的费用
            var _current = Math.Round(money * rate * 1.005M, 3).ToString();
            // 根据时间戳来获取冲值金额
            var rmbMoney = $"{ _current.Substring(0, _current.IndexOf('.') + 2) }{rndNum}";
            // 判断数据库中在10分钟之内是否有下过订单，有就重新生成
            var data = _repository.Get($"select * from UCAlipayInCash where code = 0 and Money='{rmbMoney}' and datediff(n, addTime, GETDATE()) < 10");
            if (data == null)
            {
                return rmbMoney.ToDecimal();
            }
            else
            {
                var newNum = rndNum == 9 ? 0 : rndNum + 1;
                if (defaultNum == newNum)
                {
                    return 0M;
                }
                else
                {
                    return ValidMoney(rate, money, newNum, defaultNum);
                }
            }
        }

        /// <summary>
        ///  http://www.atool.org/chinese2unicode.php
        /// </summary>
        /// <param name="inCoinId"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        public ConfirmInCashModel GetInCoinById(int inCoinId, String userId)
        {

            var result = new ConfirmInCashModel();
            var entity = _repository.Get(inCoinId);
            if (entity != null)
            {
                // 只是查找自己的记录未未完成的记录
                if ($"{entity.UserManagerId}" == userId && entity.State == 3)
                {
                    result = _mapper.Map<ConfirmInCashModel>(entity);
                    result.ManagerRealName = _bankOption?.UserName;
                    result.ManagerCardNo = _bankOption?.CardNo;
                    result.ManagerCardType = _bankOption?.CardType;
                    result.ManagerCardAddress = _bankOption?.CardAddress;
                    result.DisplayRMBMoney = $"{ Math.Round(result.RMBMoney ?? 0, 2) }元";
                }
            }

            return result;
        }

        public BaseResult AuditInCoin(int inCoinId, String userId)
        {
            var result = new BaseResult();
            var now = DateTime.Now;
            var entity = _repository.Get(inCoinId);
            if (entity == null)
            {
                result.ResultCode = ResultCodeAddMsgKeys.CommonExceptionCode;
                result.ResultMsg = ResultCodeAddMsgKeys.CommonExceptionMsg;
                return result;
            }
            if (!entity.RmmfUserId.HasValue)
            {
                result.ResultCode = ResultCodeAddMsgKeys.CommonExceptionCode;
                result.ResultMsg = ResultCodeAddMsgKeys.CommonExceptionMsg;
                return result;
            }
            if (!entity.Money.HasValue)
            {
                result.ResultCode = ResultCodeAddMsgKeys.CommonExceptionCode;
                result.ResultMsg = ResultCodeAddMsgKeys.CommonExceptionMsg;
                return result;
            }

            #region 风软审核入金逻辑(营业部人员，手工在第三方软件操作 2019-03-04)
            //// 同步风软的审核入金逻辑
            //var rmmfFlag = InCoinRmmfCash(entity.RmmfUserId.Value, entity.Money.Value);
            //if (rmmfFlag <= 0)
            //{
            //    result.ResultCode = ResultCodeAddMsgKeys.CommonExceptionCode;
            //    result.ResultMsg = ResultCodeAddMsgKeys.CommonExceptionMsg;
            //    return result;
            //}
            #endregion

            entity.ModifyManagerId = userId.ToInt32();
            entity.ModifyTime = now;
            entity.AuditTime = now;
            entity.State = 1;
            entity.Remark = "用户入金(充值成功！)";
            if (_repository.Update(entity) > 0)
            {
                result.ResultCode = ResultCodeAddMsgKeys.CommonObjectSuccessCode;
                result.ResultMsg = ResultCodeAddMsgKeys.CommonObjectSuccessMsg;
            }
            else
            {
                result.ResultCode = ResultCodeAddMsgKeys.CommonExceptionCode;
                result.ResultMsg = ResultCodeAddMsgKeys.CommonExceptionMsg;
            }

            return result;
        }

        public BaseResult AuditCustomInCoin(AuditCustomInCoinModel model, String userId)
        {
            var result = new BaseResult();
            var now = DateTime.Now;
            var entity = _repository.Get(model.Id);
            if (entity == null)
            {
                result.ResultCode = ResultCodeAddMsgKeys.CommonExceptionCode;
                result.ResultMsg = ResultCodeAddMsgKeys.CommonExceptionMsg;
                return result;
            }
            if (!entity.RmmfUserId.HasValue)
            {
                result.ResultCode = ResultCodeAddMsgKeys.CommonExceptionCode;
                result.ResultMsg = ResultCodeAddMsgKeys.CommonExceptionMsg;
                return result;
            }
            if (!entity.Money.HasValue)
            {
                result.ResultCode = ResultCodeAddMsgKeys.CommonExceptionCode;
                result.ResultMsg = ResultCodeAddMsgKeys.CommonExceptionMsg;
                return result;
            }

            #region 风软审核入金逻辑(营业部人员，手工在第三方软件操作 2019-03-04)
            //// 同步风软的审核入金逻辑
            //var rmmfFlag = InCoinRmmfCash(entity.RmmfUserId.Value, entity.Money.Value);
            //if (rmmfFlag <= 0)
            //{
            //    result.ResultCode = ResultCodeAddMsgKeys.CommonExceptionCode;
            //    result.ResultMsg = ResultCodeAddMsgKeys.CommonExceptionMsg;
            //    return result;
            //} 
            #endregion

            entity.Money = model.Money;
            entity.RMBMoney = model.RMBMoney;
            entity.ModifyManagerId = userId.ToInt32();
            entity.ModifyTime = now;
            entity.AuditTime = now;
            entity.State = 1;
            entity.Remark = "用户入金(充值成功！)";
            if (_repository.Update(entity) > 0)
            {
                result.ResultCode = ResultCodeAddMsgKeys.CommonObjectSuccessCode;
                result.ResultMsg = ResultCodeAddMsgKeys.CommonObjectSuccessMsg;
            }
            else
            {
                result.ResultCode = ResultCodeAddMsgKeys.CommonExceptionCode;
                result.ResultMsg = ResultCodeAddMsgKeys.CommonExceptionMsg;
            }

            return result;
        }


        /// <summary>
        /// 同步风软的审核入金逻辑
        /// </summary>
        /// <param name="accountId">账户ID</param>
        /// <param name="cashState">类型
        ///     1:现金汇入
        ///     2:现金汇出
        ///     3:在途
        ///     4:转汇
        /// </param>
        /// <param name="amount">数量</param>
        /// <param name="currencyCode">币种</param>
        /// <param name="remark">说明
        ///     银行卡姓名+卡号+银行名称+省份+市。字段间用逗号（，）分隔
        /// </param>
        private int InCoinRmmfCash(int rmmfUserId, decimal amount)
        {
            //USD RMB HKD
            string currencyCode = "USD";
            string remark = "用户入金";
            short cashState = 1;
            decimal absAmount = Math.Abs(amount);
            var allRmmfAccount = _rmmfAccountService.GetActiveAccountInfo();
            var account = allRmmfAccount.FirstOrDefault(p => p.UserID == rmmfUserId);
            if (account == null)
            {
                return 0;
            }
            //_rmmfCashService.AddCashChangeVerifyAsset(accountName, amount, cashState, remark);
            var result = _rmmfCashService.AddCashChange(account.ID, cashState, absAmount, currencyCode, remark);

            return result;
        }

        /// <summary>
        /// 同步风软的审核入金逻辑
        /// </summary>
        /// <param name="accountId">账户ID</param>
        /// <param name="cashState">类型
        ///     1:现金汇入
        ///     2:现金汇出
        ///     3:在途
        ///     4:转汇
        /// </param>
        /// <param name="amount">数量</param>
        /// <param name="currencyCode">币种</param>
        /// <param name="remark">说明</param>
        private int OutCoinRmmfCash(int rmmfUserId, decimal amount)
        {
            //USD RMB HKD
            string currencyCode = "USD";
            string remark = "用户出金";
            short cashState = 2;
            decimal absAmount = Math.Abs(amount);
            var allRmmfAccount = _rmmfAccountService.GetActiveAccountInfo();
            var account = allRmmfAccount.FirstOrDefault(p => p.UserID == rmmfUserId);
            if (account == null)
            {
                return 0;
            }

            //_rmmfCashService.AddCashChangeVerifyAsset(accountName, amount, cashState, remark);
            var result = _rmmfCashService.AddCashChange(account.ID, cashState, absAmount, currencyCode, remark);

            return result;
        }

        public BaseResult CancelInCoin(int inCoinId, String userId)
        {
            var result = new BaseResult();
            var entity = _repository.Get(inCoinId);
            if (entity == null)
            {
                result.ResultCode = ResultCodeAddMsgKeys.CommonExceptionCode;
                result.ResultMsg = ResultCodeAddMsgKeys.CommonExceptionMsg;
                return result;
            }

            entity.ModifyManagerId = userId.ToInt32();
            entity.ModifyTime = DateTime.Now;
            entity.State = 2;
            entity.Remark = "用户入金(审核失败！)";

            if (_repository.Update(entity) > 0)
            {
                result.ResultCode = ResultCodeAddMsgKeys.CommonObjectSuccessCode;
                result.ResultMsg = ResultCodeAddMsgKeys.CommonObjectSuccessMsg;
            }
            else
            {
                result.ResultCode = ResultCodeAddMsgKeys.CommonExceptionCode;
                result.ResultMsg = ResultCodeAddMsgKeys.CommonExceptionMsg;
            }

            return result;
        }

        /// <summary>
        /// 审核出金产生的手续费
        /// </summary>
        /// <param name="outCashRecord"></param>
        /// <returns></returns>
        private decimal AuditOutCoinServiceCharge(UCInOutCash outCashRecord) {
            var sc = 5M;
            if (outCashRecord.AddTime.Hour >= 9 && outCashRecord.AddTime.Hour <= 17)
            {
                sc = 3M;
            }
            var flag = _repository.Insert(new UCInOutCash {
                UserManagerId = outCashRecord.UserManagerId,
                RmmfUserId = outCashRecord.RmmfUserId,
                UserBankType = outCashRecord.UserBankType,
                UserBankProvince = outCashRecord.UserBankProvince,
                UserRealName = outCashRecord.UserRealName,
                UserName = outCashRecord.UserName,
                UserCardNo = outCashRecord.UserCardNo,
                ManagerRealName = outCashRecord.ManagerRealName,
                ManagerCardNo = outCashRecord.ManagerCardNo,
                OrderNo = outCashRecord.OrderNo,
                //MoneyType = outCashRecord.MoneyType,
                //Money = outCashRecord.Money,
                RMBMoney = sc,
                //ExchangeRate = outCashRecord.ExchangeRate,
                AuditTime = outCashRecord.AuditTime,
                State = 1,
                CashType = 4,
                //CashModel = outCashRecord.CashModel,
                IP = outCashRecord.IP,
                Remark = "出金手续费",
                AddManagerId = outCashRecord.AddManagerId,
                AddTime = DateTime.Now
            });
            return flag > 0 ? sc : 0;
        }
        /// <summary>
        /// 审核出金
        /// </summary>
        /// <param name="inCoinId"></param>
        /// <param name="userId"></param>
        /// <returns></returns>

        public BaseResult AuditOutCoin(int inCoinId, String userId)
        {
            var result = new BaseResult();
            var now = DateTime.Now;
            var entity = _repository.Get(inCoinId);
            if (entity == null)
            {
                result.ResultCode = ResultCodeAddMsgKeys.CommonExceptionCode;
                result.ResultMsg = ResultCodeAddMsgKeys.CommonExceptionMsg;
                return result;
            }

            entity.ModifyManagerId = userId.ToInt32();
            entity.ModifyTime = now;
            entity.AuditTime = now;
            entity.State = 1;
            entity.Remark = "用户出金（出金成功）";
            // 同步风软的审核出金逻辑 TODO

            var scMoney = AuditOutCoinServiceCharge(entity);
            if (scMoney > 0)
            {
                // 出金金额为负数据，所以应该是 加3块
                //entity.RMBMoney -= scMoney;
                entity.RMBMoney += scMoney;
                if (_repository.Update(entity) > 0)
                {

                    result.ResultCode = ResultCodeAddMsgKeys.CommonObjectSuccessCode;
                    result.ResultMsg = ResultCodeAddMsgKeys.CommonObjectSuccessMsg;
                }
                else
                {
                    result.ResultCode = ResultCodeAddMsgKeys.CommonExceptionCode;
                    result.ResultMsg = ResultCodeAddMsgKeys.CommonExceptionMsg;
                }
            }
            else
            {
                result.ResultCode = ResultCodeAddMsgKeys.CommonExceptionCode;
                result.ResultMsg = ResultCodeAddMsgKeys.CommonExceptionMsg;
            }

            return result;
        }
        /// <summary>
        /// 审核 美付宝代付出金
        /// 1.美付宝代付接口
        /// 2.判断风软那边资金是否够用
        /// </summary>
        /// <param name="inCoinId"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        public BaseResult AuditGomePayOutCoin(int inCoinId, String userId, string gomePayPwd)
        {
            var result = new BaseResult();
            var now = DateTime.Now;
            var entity = _repository.Get(inCoinId);
            if (entity == null)
            {
                result.ResultCode = ResultCodeAddMsgKeys.CommonExceptionCode;
                result.ResultMsg = ResultCodeAddMsgKeys.CommonExceptionMsg;
                return result;
            }
            entity.ModifyManagerId = userId.ToInt32();
            entity.ModifyTime = now;
            entity.AuditTime = now;
            entity.State = 1;
            entity.Remark = "用户出金（美付宝出金成功）";
            // 2.如果余额小于0 用户不能出金
            var rmmfOutCoin = _rmmfCashService.GetRealTimeAsset(entity.UserName);
            var rmmfTotalMoney = Math.Floor(rmmfOutCoin.BuyingPower);
            if (rmmfTotalMoney < 0)
            {
                result.ResultCode = ResultCodeAddMsgKeys.InOutCoinMoneyInsufficientCode;
                result.ResultMsg = ResultCodeAddMsgKeys.GomePayRmmfAccountBalanceErrorMsg;
                return result;
            }
            var scMoney = AuditOutCoinServiceCharge(entity);
            if (scMoney > 0)
            {
                // 出金金额为负数据，所以应该是 加3块
                //entity.RMBMoney -= scMoney;
                entity.RMBMoney += scMoney;

                /// 1.增加美付宝代付  2019-4-3
                var gomePayDFModel = _mapper.Map<GomePayDFAddModel>(entity);

                gomePayDFModel.PayPassword = gomePayPwd;
                var gomePayResult = _ucGomePayDFService.AddGomePayDaiFu(gomePayDFModel, userId);
                if (gomePayResult.Success)
                {
                    if (_repository.Update(entity) > 0)
                    {
                        result.ResultCode = ResultCodeAddMsgKeys.CommonObjectSuccessCode;
                        result.ResultMsg = ResultCodeAddMsgKeys.CommonObjectSuccessMsg;
                    }
                    else
                    {
                        result.ResultCode = ResultCodeAddMsgKeys.CommonExceptionCode;
                        result.ResultMsg = ResultCodeAddMsgKeys.CommonExceptionMsg;
                    }
                }
                else
                {
                    result.ResultCode = ResultCodeAddMsgKeys.CommonExceptionCode;
                    result.ResultMsg = gomePayResult.ResultMsg;
                }
            }
            else
            {
                result.ResultCode = ResultCodeAddMsgKeys.CommonExceptionCode;
                result.ResultMsg = ResultCodeAddMsgKeys.CommonExceptionMsg;
            }
            return result;
        }
        /// <summary>
        /// 获取账户余额
        /// </summary>
        /// <param name="username"></param>
        /// <returns></returns>

       public TableDataResult<RmmfAccountBalanceOutput> GetRmmfAccountBalanceByUserName(string username)
       {

        //    AccountName String  账户名称
        //    ///                 BuyingPower double 可用资金
        //    ///                 CashInOut double 现金存取
        //    ///                 Credit double 信用额度
        //    ///                 NLV double 平仓权益
        //    ///                 LUC double 冻结资产
        //    ///                 TotalMargin double 总保证金
        //    ///                 NLV_RMB double 平仓权益（RMB）
        //    ///                 Currency String  该账户的结算货币
            var result = new TableDataResult<RmmfAccountBalanceOutput>();
            var data = _rmmfCashService.GetRealTimeAsset(username);
            result.Data = new RmmfAccountBalanceOutput()
            {
                Currency=data.Currency,
                BuyingPower = data.BuyingPower,
                LUC = data.LUC
            };
            return result;
        }
        /// <summary>
        /// 获取gome pay  支付结果
        /// </summary>
        /// <param name="username"></param>
        /// <returns></returns>
        public TableDataResult<GomePayDFBillOutput> GetGomePayOrderState(string orderNo)
        {

            var result = new TableDataResult<GomePayDFBillOutput>();
            result = _ucGomePayDFService.GetGomePayDFBillByOrderNo(orderNo);
            
            return result;

        }




        public BaseResult CancelOutCoin(int inCoinId, String userId)
        {
            var result = new BaseResult();
            var entity = _repository.Get(inCoinId);
            if (entity == null)
            {
                result.ResultCode = ResultCodeAddMsgKeys.CommonExceptionCode;
                result.ResultMsg = ResultCodeAddMsgKeys.CommonExceptionMsg;
                return result;
            }
            if (!entity.RmmfUserId.HasValue)
            {
                result.ResultCode = ResultCodeAddMsgKeys.CommonExceptionCode;
                result.ResultMsg = ResultCodeAddMsgKeys.CommonExceptionMsg;
                return result;
            }
            if (!entity.Money.HasValue)
            {
                result.ResultCode = ResultCodeAddMsgKeys.CommonExceptionCode;
                result.ResultMsg = ResultCodeAddMsgKeys.CommonExceptionMsg;
                return result;
            }

#if !DEBUG 
            // 同步风软的审核出金逻辑 TODO
            var rmmfFlag = InCoinRmmfCash(entity.RmmfUserId.Value, entity.Money.Value);
            if (rmmfFlag <= 0)
            {
                result.ResultCode = ResultCodeAddMsgKeys.CommonExceptionCode;
                result.ResultMsg = ResultCodeAddMsgKeys.CommonExceptionMsg;
                return result;
            }
#endif
            entity.ModifyManagerId = userId.ToInt32();
            entity.ModifyTime = DateTime.Now;
            entity.State = 2;
            entity.Remark = "用户出金（审核失败）";
            if (_repository.Update(entity) > 0)
            {
                result.ResultCode = ResultCodeAddMsgKeys.CommonObjectSuccessCode;
                result.ResultMsg = ResultCodeAddMsgKeys.CommonObjectSuccessMsg;
            }
            else
            {
                result.ResultCode = ResultCodeAddMsgKeys.CommonExceptionCode;
                result.ResultMsg = ResultCodeAddMsgKeys.CommonExceptionMsg;
            }

            return result;
        }

        public BaseResult AuditConfirmInCoin(ConfirmInCashModel item, String userId)
        {
            var result = new BaseResult();
            var entity = _repository.Get(item.Id);
            if (entity == null)
            {
                result.ResultCode = ResultCodeAddMsgKeys.CommonExceptionCode;
                result.ResultMsg = ResultCodeAddMsgKeys.CommonExceptionMsg;
                return result;
            }

            entity.ManagerRealName = item.ManagerRealName;
            entity.ManagerCardNo = item.ManagerCardNo;
            entity.UserRealName = item.UserRealName;
            entity.UserCardNo = item.UserCardNo;
            entity.ModifyManagerId = userId.ToInt32();
            entity.ModifyTime = DateTime.Now;
            entity.State = 0;

            if (_repository.Update(entity) > 0)
            {
                result.ResultCode = ResultCodeAddMsgKeys.CommonObjectSuccessCode;
                result.ResultMsg = ResultCodeAddMsgKeys.CommonObjectSuccessMsg;
            }
            else
            {
                result.ResultCode = ResultCodeAddMsgKeys.CommonExceptionCode;
                result.ResultMsg = ResultCodeAddMsgKeys.CommonExceptionMsg;
            }

            return result;
        }
        /// <summary>
        /// 出金逻辑
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        public BaseResult AddOrModifyOutCoin(OutCashModel item)
        {
            var result = new BaseResult();
            UCInOutCash entity;
            var now = DateTime.Now;
            if (item.Id == 0)
            {
                //var rate = _ucExchangeRateRepository.GetDefaultExchangeRate();    
                var resultData = _ucExchangeRateManagerService.GetInOutExchangeRateByManagerId(item.ManagerId.ToString());  //2019/3/12
                var rate = resultData.Data;
                if (rate == null)
                {
                    result.ResultCode = ResultCodeAddMsgKeys.ExchangeRateFailNoDataCode;
                    result.ResultMsg = ResultCodeAddMsgKeys.ExchangeRateFailNoDataMsg;
                    return result;
                }
                var manager = _managerRepository.Get(item.ManagerId);
                if (manager == null)
                {
                    result.ResultCode = ResultCodeAddMsgKeys.CommonExceptionCode;
                    result.ResultMsg = ResultCodeAddMsgKeys.CommonExceptionMsg;
                    return result;
                }
                if (manager.BankCard.IsNullOrWhiteSpace())
                {
                    result.ResultCode = ResultCodeAddMsgKeys.CommonExceptionCode;
                    result.ResultMsg = ResultCodeAddMsgKeys.CommonExceptionMsg;
                    return result;
                }
                if (!item.RmmfUserId.HasValue)
                {
                    result.ResultCode = ResultCodeAddMsgKeys.CommonExceptionCode;
                    result.ResultMsg = ResultCodeAddMsgKeys.CommonExceptionMsg;
                    return result;
                }
                // 再次验证风软的金额
                var rmmfOutCoin = _rmmfCashService.GetRealTimeAsset(manager.UserName);
                var rmmfTotalMoney = Math.Floor(rmmfOutCoin.BuyingPower);
                if (item.Money > rmmfTotalMoney)
                {
                    result.ResultCode = ResultCodeAddMsgKeys.InOutCoinMoneyInsufficientCode;
                    result.ResultMsg = ResultCodeAddMsgKeys.InOutCoinMoneyInsufficientMsg;
                    return result;
                }
                var orderNo = $"{manager.UserName}{now.ToString("yyyyMMddHHmmss")}";
                var isExist = _repository.Get("select top 1 * from UCInOutCash where OrderNo=@orderNo", new { orderNo = orderNo });
                if (isExist != null)
                {
                    result.ResultCode = ResultCodeAddMsgKeys.InOutCoinRepeatOrderCode;
                    result.ResultMsg = ResultCodeAddMsgKeys.InOutCoinRepeatOrderMsg;
                    return result;
                }
                var BankProvince = "";
                var BankCard = "";
                var BankType = "";
                var managerBank = _managerBankCardRepository.GetManagerBankCardByManagerId(manager.Id);
                if (managerBank !=null && !managerBank.BankCard.IsNullOrWhiteSpace())
                {
                    BankProvince = managerBank.BankProvince;
                    BankCard = managerBank.BankCard;
                    BankType = managerBank.BankType;
                }
                else if (!manager.BankCard.IsNullOrWhiteSpace())
                {
                    BankProvince = manager.BankProvince;
                    BankCard = manager.BankCard;
                    BankType = manager.BankType;
                }
                entity = _mapper.Map<UCInOutCash>(item);
                entity.UserManagerId = item.ManagerId;
                entity.UserName = manager.UserName;
                entity.UserRealName = manager.RealName;
                //充值中心银行卡
                entity.UserBankProvince = BankProvince;
                entity.UserCardNo = BankCard;
                entity.UserBankType = BankType;
                entity.OrderNo = orderNo;
                entity.MoneyType = rate.OutCoinUnitCode;    //出金币种
                entity.Money = -item.Money;
                entity.ExchangeRate = rate.OutCoinExchangeRate; //出金汇率
                entity.RMBMoney = -item.Money * rate.OutCoinExchangeRate;   //出金汇率
                entity.State = 0;
                entity.CashType = 1;
                entity.CashModel = 1;
                entity.Remark = "用户出金(待审核)";
                entity.IsDelete = false;
                entity.AddTime = now;
                entity.AddManagerId = item.ManagerId;
                if (_repository.Insert(entity) > 0)
                {
                    // [锁定]风软出金 
                    var rmmfFlag = OutCoinRmmfCash(item.RmmfUserId.Value, item.Money);
                    if (rmmfFlag > 0)
                    {
                        result.ResultCode = ResultCodeAddMsgKeys.CommonObjectSuccessCode;
                        result.ResultMsg = ResultCodeAddMsgKeys.CommonObjectSuccessMsg;
                    }
                    else
                    {
                        // 同步风软
                        _repository.Delete(entity.Id);

                        result.ResultCode = ResultCodeAddMsgKeys.InOutCoinErrorCode;
                        result.ResultMsg = ResultCodeAddMsgKeys.InOutCoinErrorMsg;
                    }
                }
                else
                {
                    result.ResultCode = ResultCodeAddMsgKeys.CommonExceptionCode;
                    result.ResultMsg = ResultCodeAddMsgKeys.CommonExceptionMsg;
                }
            }
            else
            {
                ////TODO Modify
                //tradeCommission = _repository.Get(item.Id);
                //if (tradeCommission != null)
                //{
                //    _mapper.Map(item, tradeCommission);
                //    tradeCommission.ModifyManagerId = userId;
                //    tradeCommission.ModifyTime = now;
                //    if (_repository.Update(tradeCommission) > 0)
                //    {
                //        result.ResultCode = ResultCodeAddMsgKeys.CommonObjectSuccessCode;
                //        result.ResultMsg = ResultCodeAddMsgKeys.CommonObjectSuccessMsg;
                //    }
                //    else
                //    {
                //        result.ResultCode = ResultCodeAddMsgKeys.CommonExceptionCode;
                //        result.ResultMsg = ResultCodeAddMsgKeys.CommonExceptionMsg;
                //    }
                //}
                //else
                //{
                //    result.ResultCode = ResultCodeAddMsgKeys.CommonFailNoDataCode;
                //    result.ResultMsg = ResultCodeAddMsgKeys.CommonFailNoDataMsg;
                //}
            }
            return result;
        }
        #endregion

        #region 1.2 获取用户出入金用户信息
        public TableDataResult<InCoinUserModel> LoadInCoinUserData(string UserId, string RoleId)
        {
            var result = new TableDataResult<InCoinUserModel>();
            var _userId = 0;
            var exchangeRate = _ucExchangeRateManagerService.GetInOutExchangeRateByManagerId(UserId);

            if (int.TryParse(UserId, out _userId))
            {
                //判断入金汇率
                if (exchangeRate.Data != null)
                {
                    var manager = _managerRepository.Get(_userId);
                    if (manager != null)
                    {
                        var inCoinUser = _mapper.Map<InCoinUserModel>(manager);
                        inCoinUser.ManagerId = manager.Id;
                        var rmmfOutCoin = _rmmfCashService.GetRealTimeAsset(inCoinUser.UserName);
                        inCoinUser.TotalMoney = Math.Floor(rmmfOutCoin.BuyingPower);
                        if (inCoinUser.TotalMoney < 0)
                        {
                            inCoinUser.TotalMoney = 0;
                        }
                        //inCoinUser.TotalMoney = _repository.SumMoneyByUserId(UserId);


                        // inCoinUser.ExchangeRate = _ucExchangeRateRepository.GetDefaultExchangeRate()?.ProjectPrice; 
                        //支付宝汇率取默认
                        inCoinUser.AliPayExchangeRate = _ucExchangeRateRepository.GetDefaultExchangeRate()?.ProjectPrice;
                        inCoinUser.ExchangeRate = exchangeRate.Data.InCoinExchangeRate; //入金汇率 by zzc 2019/3/11

                        result.Data = inCoinUser;
                        result.ResultCode = ResultCodeAddMsgKeys.CommonObjectSuccessCode;
                        result.ResultMsg = ResultCodeAddMsgKeys.CommonObjectSuccessMsg;
                    }
                    else
                    {
                        //失败
                        result.ResultCode = ResultCodeAddMsgKeys.CommonExceptionCode;
                        result.ResultMsg = ResultCodeAddMsgKeys.CommonExceptionMsg;
                    }
                }
                else
                {
                    //汇率获取失败
                    result.ResultCode = ResultCodeAddMsgKeys.ExchangeRateFailNoDataCode;
                    result.ResultMsg = ResultCodeAddMsgKeys.ExchangeRateFailNoDataMsg;
                }
            }
            else
            {
                //失败
                result.ResultCode = ResultCodeAddMsgKeys.CommonExceptionCode;
                result.ResultMsg = ResultCodeAddMsgKeys.CommonExceptionMsg;
            }

            return result;
        }
        /// <summary>
        /// 获取用户出金的相关信息
        /// </summary>
        /// <param name="UserId"></param>
        /// <param name="RoleId"></param>
        /// <returns></returns>
        public TableDataResult<OutCoinUserModel> LoadOutCoinUserData(string UserId, string RoleId)
        {
            var result = new TableDataResult<OutCoinUserModel>();
            var _userId = 0;
            var exchangeRate = _ucExchangeRateManagerService.GetInOutExchangeRateByManagerId(UserId);

            if (int.TryParse(UserId, out _userId))
            {
                //汇率判断
                if (exchangeRate.Data != null)
                {
                    var manager = _managerRepository.Get(_userId);
                    if (manager != null)
                    {
                        var outCoinUser = _mapper.Map<OutCoinUserModel>(manager);
                        var bankCard = "";
                        //处理充值中心银行卡的问题
                        var _BankCard = "";
                       var managerBank=_managerBankCardRepository.GetManagerBankCardByManagerId(_userId);
                        if (managerBank !=null && !managerBank.BankCard.IsNullOrWhiteSpace()) {
                            _BankCard = _desService.DecryptBankAccount(managerBank.BankCard);
                            var lenBank = _BankCard.Length;
                            bankCard = lenBank > 4 ? _BankCard.Substring(lenBank - 4, 4) : _BankCard;
                        }
                        else if (!outCoinUser.BankCard.IsNullOrWhiteSpace())
                        {
                            _BankCard = _desService.DecryptBankAccount(outCoinUser.BankCard);
                            var len = _BankCard.Length;
                            bankCard = len > 4 ? _BankCard.Substring(len - 4, 4) : _BankCard;
                        }
                        outCoinUser.ManagerId = manager.Id;
                        outCoinUser.BankCard = $"****{ bankCard }";
                        //outCoinUser.TotalMoney = _repository.SumMoneyByUserId(UserId);
                        var rmmfOutCoin = _rmmfCashService.GetRealTimeAsset(outCoinUser.UserName);
                        outCoinUser.TotalMoney = Math.Floor(rmmfOutCoin.BuyingPower);
                        if (outCoinUser.TotalMoney < 0)
                        {
                            outCoinUser.TotalMoney = 0;
                        }
                        //outCoinUser.ExchangeRate = _ucExchangeRateRepository.GetDefaultExchangeRate()?.ProjectPrice;
                        outCoinUser.ExchangeRate = exchangeRate.Data.OutCoinExchangeRate;  //获取出金汇率规则 zzc by 2019/3/11
                        result.Data = outCoinUser;
                        result.ResultCode = ResultCodeAddMsgKeys.CommonObjectSuccessCode;
                        result.ResultMsg = ResultCodeAddMsgKeys.CommonObjectSuccessMsg;
                    }
                    else
                    {
                        //失败
                        result.ResultCode = ResultCodeAddMsgKeys.CommonExceptionCode;
                        result.ResultMsg = ResultCodeAddMsgKeys.CommonExceptionMsg;
                    }
                }
                else
                {
                    //汇率获取失败
                    result.ResultCode = ResultCodeAddMsgKeys.ExchangeRateFailNoDataCode;
                    result.ResultMsg = ResultCodeAddMsgKeys.ExchangeRateFailNoDataMsg;
                }
            }
            else
            {
                //失败
                result.ResultCode = ResultCodeAddMsgKeys.CommonExceptionCode;
                result.ResultMsg = ResultCodeAddMsgKeys.CommonExceptionMsg;
            }

            return result;
        }
        #endregion

        #region 1.1 直客出入金查询
        public TableDataModel LoadInCoinRecordData(InOutCoinRecordRequestModel model, String userId, String roleId)
        {
            // CashType 出入金类型： 1.出金；2.线下入金； 3.线上入金；
            // State入金： 0：待审核；1：入金完成；2：入金失败；3：生成订单；
            string conditions = $"where IsDelete=0 and CashType in(2,3) and State in(0,1,2) ";// 当前用户未删除的所有入金记录
            if (roleId == "6")
            {
                conditions += $"and UserManagerId={userId} ";
            }
            else
            {
                conditions += $"and UserManagerId in(select Id from Manager where Id={userId} or AddManagerId={userId}) ";
            }
            return LoadData(model, conditions);
        }
        /// <summary>
        /// 出金记录 
        /// </summary>
        public TableDataModel LoadOutCoinRecordData(InOutCoinRecordRequestModel model, String userId, String roleId)
        {
            // CashType 出入金类型： 1.出金；2.线下入金； 3.线上入金；
            string conditions = $"where IsDelete=0 and CashType =1 ";// 当前用户未删除的所有入金记录
            if (roleId == "6")
            {
                conditions += $"and UserManagerId={userId} ";
            }
            else
            {
                conditions += $"and UserManagerId in(select Id from Manager where Id={userId} or AddManagerId={userId}) ";
            }
            return LoadData(model, conditions);
        }
        #endregion

        #endregion

        #region 2. 营业部

        #region 2.1 营业部出入金查询
        /// <summary>
        /// 出金
        /// </summary>
        /// <param name="model"></param>
        /// <param name="userId"></param>
        /// <param name="roleId"></param>
        /// <returns></returns>
        public TableDataModel LoadOutCashRecordData(InOutCoinRecordRequestModel model, String userId, String roleId)
        {
            // CashType 出入金类型： 1.出金；2.线下入金； 3.线上入金；
            string conditions = $"where IsDelete=0 and CashType =1 ";// 未删除的所有入金记录
            return LoadData(model, conditions);
        }

        /// <summary>
        /// 线上入金
        /// </summary>
        /// <param name="model"></param>
        /// <param name="userId"></param>
        /// <param name="roleId"></param>
        /// <returns></returns>
        public TableDataModel LoadOnlineInCashRecordData(InOutCoinRecordRequestModel model, String userId, String roleId)
        {
            // CashType 出入金类型： 1.出金；2.线下入金； 3.线上入金；
            string conditions = $"where IsDelete=0 and CashType =3 ";// 未删除的所有入金记录
            return LoadData(model, conditions);
        }

        /// <summary>
        /// 线下入金
        /// </summary>
        /// <param name="model"></param>
        /// <param name="userId"></param>
        /// <param name="roleId"></param>
        /// <returns></returns>
        public TableDataModel LoadOfflineInCashRecordData(InOutCoinRecordRequestModel model, String userId, String roleId)
        {
            // CashType 出入金类型： 1.出金；2.线下入金； 3.线上入金；
            // State入金： 0：待审核；1：入金完成；2：入金失败；3：生成订单；
            string conditions = $"where IsDelete=0 and CashType =2 and State in(0,1,2) ";// 未删除的所有入金记录
            if (model.State.HasValue)
            {
                if (model.State == 3) conditions = $"where IsDelete=0 and CashType =2 and State =3 ";// 未删除的所有入金记录
            }
           
            return LoadData(model, conditions);
        }
        #endregion
        #endregion

        #region 3. 出入金记录
        /// <summary>
        /// 出入金记录
        /// </summary>
        TableDataModel LoadData(InOutCoinRecordRequestModel model, String conditions)
        {
            string Key = "";

            if (!model.Key.IsNullOrWhiteSpace())
            {
                conditions += $"and (UserRealName like @Key or UserName like  @Key) ";
                Key = model.Key.ToSqlLikeParam();

            }
            if (model.State.HasValue)
            {
                conditions += $"and State = {model.State} ";
            }
            if (model.Start.HasValue)
            {
                conditions += $"and AddTime >='{ model.Start.Value }' ";
            }
            if (model.End.HasValue)
            {
                conditions += $"and AddTime <='{ model.End.Value.Date.AddDays(1).AddSeconds(-1) }' ";
            }
            if (!model.ManagerId.IsNullOrWhiteSpace())
            {
                conditions += $"and UserManagerId = {model.ManagerId} ";
            }
            var list = _repository.GetListPaged(model.Page, model.Limit, conditions, "AddTime desc,Id desc", new
            {
                Key = Key
            }).ToList();

            var result = new List<UCInOutCash>();
            foreach (var item in list)
            {
                item.Money = Math.Abs(item.Money ?? 0);
                item.RMBMoney = Math.Abs(item.RMBMoney ?? 0);
                result.Add(item);
            }
            return new TableDataModel
            {
                count = _repository.RecordCount(conditions, new { Key = Key }),
                data = result
            };
        }

        #endregion
        //TableDataResult<>


        public BaseResult DeleteIds(int[] Ids)
        {
            var result = new BaseResult();
            if (Ids.Count() == 0)
            {
                result.ResultCode = ResultCodeAddMsgKeys.CommonModelStateInvalidCode;
                result.ResultMsg = ResultCodeAddMsgKeys.CommonModelStateInvalidMsg;
            }
            else
            {
                var count = _repository.DeleteLogical(Ids);
                if (count > 0)
                {
                    //成功
                    result.ResultCode = ResultCodeAddMsgKeys.CommonObjectSuccessCode;
                    result.ResultMsg = ResultCodeAddMsgKeys.CommonObjectSuccessMsg;
                }
                else
                {
                    //失败
                    result.ResultCode = ResultCodeAddMsgKeys.CommonExceptionCode;
                    result.ResultMsg = ResultCodeAddMsgKeys.CommonExceptionMsg;
                }
            }
            return result;
        }

    }
}